<template>
  <div class="member-container">
    <!-- 搜索表单 -->
    <el-form ref="searchForm" :model="searchForm" inline size="small" class="search-form">
      <el-form-item label="会员姓名">
        <el-input v-model="searchForm.name" placeholder="请输入会员姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增会员</el-button>
      </el-form-item>
    </el-form>

    <!-- 会员列表表格 -->
    <el-table
      :data="memberList"
      border
      stripe
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="memberId" label="会员ID" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80">
        <template slot-scope="scope">
          {{ scope.row.gender === '男' ? '男' : scope.row.gender === '女' ? '女' : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="130"></el-table-column>
      <el-table-column prop="birthday" label="生日" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right;"
    >
    </el-pagination>

    <!-- 新增/编辑会员对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="memberForm"
        :model="memberForm"
        :rules="memberRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username" v-if="!isEdit">
              <el-input v-model="memberForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="memberForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="memberForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="memberForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="memberForm.birthday"
                type="date"
                placeholder="请选择生日"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="memberForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="memberForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="memberForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看会员详情对话框 -->
    <el-dialog
      title="会员详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会员ID">{{ memberDetail.memberId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ memberDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ memberDetail.gender || '-' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ memberDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="生日">{{ memberDetail.birthday || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ memberDetail.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ memberDetail.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(memberDetail.status)">
            {{ getStatusText(memberDetail.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { queryMembers, saveMember, updateMember, deleteMember, getMemberDetail } from '@/api/member'

export default {
  name: 'Member',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        phone: ''
      },
      // 会员列表
      memberList: [],
      loading: false,
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitLoading: false,
      // 会员表单
      memberForm: {
        memberId: '',
        username: '',
        name: '',
        gender: '',
        phone: '',
        birthday: '',
        email: '',
        address: '',
        password: ''
      },
      // 表单验证规则
      memberRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 详情对话框
      detailDialogVisible: false,
      memberDetail: {}
    }
  },
  mounted() {
    this.loadMemberList()
  },
  methods: {
    // 加载会员列表
    async loadMemberList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          name: this.searchForm.name || null,
          phone: this.searchForm.phone || null
        }
        const response = await queryMembers(params)
        // 兼容axios封装后的response结构
        const res = response.data ? response.data : response
        if (res.code === 1) {
          this.memberList = (res.data.records || []).map(item => ({
            ...item,
            birthday: Array.isArray(item.birthday) ? item.birthday.join('-') : item.birthday
          }))
          this.pagination.total = res.data.total || 0
        } else {
          this.$message.error(res.msg || '查询失败')
        }
      } catch (error) {
        console.error('查询会员列表失败:', error)
        this.$message.error('查询失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadMemberList()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: '',
        phone: ''
      }
      this.pagination.page = 1
      this.loadMemberList()
    },

    // 新增会员
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增会员'
      this.memberForm = {
        memberId: '',
        username: '',
        name: '',
        gender: '',
        phone: '',
        birthday: '',
        email: '',
        address: '',
        password: ''
      }
      this.dialogVisible = true
    },

    // 编辑会员
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑会员'
      this.memberForm = {
        memberId: row.memberId,
        username: row.username,
        name: row.name,
        gender: row.gender,
        phone: row.phone,
        birthday: row.birthday ? new Date(row.birthday) : '', // 保证为Date对象
        email: row.email,
        address: row.address,
        password: '' // 编辑时密码可选填，不显示输入框
      }
      this.dialogVisible = true
    },

    // 查看会员详情
    async handleView(row) {
      try {
        const response = await getMemberDetail(row.memberId)
        const res = response.data ? response.data : response
        if (res.code === 1) {
          this.memberDetail = res.data
          this.detailDialogVisible = true
        } else {
          this.$message.error(res.msg || '获取详情失败')
        }
      } catch (error) {
        this.$message.error('获取详情失败')
      }
    },

    // 删除会员
    handleDelete(row) {
      this.$confirm(`确定要删除会员"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteMember(row.memberId)
          const res = response.data ? response.data : response
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.loadMemberList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 提交表单
    handleSubmit() {
      this.$refs.memberForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            let response
            if (this.isEdit) {
              response = await updateMember(this.memberForm)
            } else {
              response = await saveMember(this.memberForm)
            }
            const res = response.data ? response.data : response
            if (res.code === 1) {
              this.$message.success(this.isEdit ? '修改成功' : '添加成功')
              this.dialogVisible = false
              this.loadMemberList()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error('操作失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },

    // 关闭对话框
    handleDialogClose() {
      this.$refs.memberForm.resetFields()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.page = 1
      this.loadMemberList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadMemberList()
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '有效',
        2: '过期',
        3: '冻结'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.member-container {
  padding: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-bottom: 20px;
}

.el-descriptions {
  margin-top: 20px;
}
</style>